package com.google.code.csf.locators.jaxws;

import com.google.code.csf.locators.AbstractWebServiceServiceLocator;

import java.util.Map;

public abstract class AbstractJaxWsServiceLocator extends AbstractWebServiceServiceLocator {

    public Object locate(Class toLocate) throws Throwable {
        Object bindingProvider = locateJaxService();
        Class bindingProviderClass = bindingProvider.getClass();
        Map requestContext = (Map) bindingProviderClass.getMethod("getRequestContext", null).invoke(bindingProvider, null);
        if (getEndpointAddress() != null) {
            requestContext.put(bindingProviderClass.getField("ENDPOINT_ADDRESS_PROPERTY").get(bindingProvider), getEndpointAddress());
        }
        if (isMaintainSession()) {
            requestContext.put(bindingProviderClass.getField("SESSION_MAINTAIN_PROPERTY").get(bindingProvider), isMaintainSession() ? Boolean.TRUE : Boolean.FALSE);
        }
        if (getUsername() != null) {
            requestContext.put(bindingProviderClass.getField("USERNAME_PROPERTY").get(bindingProvider), getUsername());
        }
        if (getPassword() != null) {
            requestContext.put(bindingProviderClass.getField("PASSWORD_PROPERTY").get(bindingProvider), getPassword());
        }
        return bindingProvider;
    }
}
